package com.hero.take.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件读写类
 * 参考文献：https://blog.csdn.net/m0_50744075/article/details/125888541
 */
public class FileHelper {

    /**
     * 一次性读取文件全部内容
     * @param filePath
     * @throws IOException
     */
    public static String readAll(String filePath) throws IOException {
        //filePath = "E:\\projects\\扁平化指挥\\source\\JXXTZH-ZZD\\pages\\index\\index_zzd_demo.js";
        InputStream is = new FileInputStream(filePath);
        int iAvail = is.available();
        byte[] bytes = new byte[iAvail];
        is.read(bytes);
        String cnt = new String(bytes);
        System.out.println(cnt);
        is.close();
        return cnt;
    }

    /**
     * 字符流按行读取文件
     * @param filePath
     */
    public static List<String> readByLine(String filePath) throws IOException {
        File file = new File(filePath);
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String strLine = null;
        int lineCount = 1;
        List<String> listStr = new ArrayList<>();
        while(null != (strLine = bufferedReader.readLine())){
            System.out.println("第[" + lineCount + "]行数据:[" + strLine + "]");
            listStr.add(strLine);
            lineCount++;
        }
        return listStr;
    }

    /**
     * 写文件
     * @param filePath
     * @param s
     * @throws Exception
     */
    public static void write(String filePath, String s) throws Exception {
        File file = new File(filePath);
        OutputStream out = null;
        BufferedWriter bw = null;
        if (!file.exists()) {
            file.createNewFile();
        }
        out = new FileOutputStream(file);
        bw = new BufferedWriter(new OutputStreamWriter(out, "utf-8"));
        bw.write(s);
        bw.flush();
        bw.close();
    }
}
